using System.Net.WebSockets;
using GameKit.Core;
using GameKit.Core.Context;
using GameKitUnity.Network;
using OneGame;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using System;
using GameKitUnity.UI;

public class TestSocket : MonoBehaviour
{
    [SerializeField]
    private SocketConfig socketConfig;

    [SerializeField]
    private TextMeshProUGUI actionText;

    [SerializeField]
    private float sendInterval = 0.2f;

    [SerializeField]
    private Transform playerTransform;

    private GameSocket _gameSocket;
    private bool _isConnected;
    private float _timer;

    private void Start()
    {
        GetComponent<Button>().onClick.AddListener(() =>
        {
            OpenTaskPanel();
            switch (_gameSocket)
            {
                case null:
                    _gameSocket = new GameSocket($"{socketConfig.host}:{socketConfig.port}");
                    InitSocket(_gameSocket);
                    break;
                case { State : WebSocketState.Open }:
                    _gameSocket.Close();
                    break;
            }
        });
    }

    private async void OpenTaskPanel()
    {
        const string taskPanel = "Assets/1Game/Prefabs/UI/TaskPanel.prefab";
        var panel = await UIKit.Instance.OpenPanelAsync(this, taskPanel);
        panel.OnDestroyEvent += () => { SceneManager.Instance.LoadScene("PreloadScene"); };
    }

    private void InitSocket(ISocket socket)
    {
        socket.OnOpen = () =>
        {
            Log.Info("Socket Opened");
            actionText.text = "Disconnect";
            _isConnected = true;
        };
        socket.OnBinary = bytes =>
        {
            Log.Info($"Socket Received Data: {bytes.Length} bytes");
            sbyte type = unchecked((sbyte)bytes[0]); // Message type
            if (type == 0x01)
            {
                var id = BitConverter.ToInt32(bytes, 1);
                var x = BitConverter.ToSingle(bytes, 3);
                var y = BitConverter.ToSingle(bytes, 7);
                var z = BitConverter.ToSingle(bytes, 11);
                Log.Info($"Received Position Update: id: {id} position: ({x}, {y}, {z})");
            }
        };
        socket.OnClose = () =>
        {
            Log.Info("Socket Closed");
            actionText.text = "Connect";
            _isConnected = false;
        };
        socket.OnError = exception => { Log.Error($"Socket Error: {exception.Message}"); };

        // 注册到全局Socket系统
        GlobalContext.GetSystem<SocketSystem>().Connect("GameSocket", _gameSocket);
    }

    private void Update()
    {
        _timer += Time.deltaTime;
        if (_timer < sendInterval) return;
        _timer = 0f;
        if (_isConnected)
        {
            var data = new byte[13]; // 不需要给id，服务器会分配
            data[0] = 0x00; // Message type for position update
            var pos = playerTransform.position;
            Buffer.BlockCopy(BitConverter.GetBytes(pos.x), 0, data, 1, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(pos.y), 0, data, 5, 4);
            Buffer.BlockCopy(BitConverter.GetBytes(pos.z), 0, data, 9, 4);
            _gameSocket.Send(data);
            Log.Info($"Socket Sent Data: {data.Length} bytes");
        }
    }
}